<!DOCTYPE html>
<html lang="zh-CN">





<head>
  <meta charset="UTF-8">
  <link rel="apple-touch-icon" sizes="76x76" href="/blog/img/favicon.png">
  <link rel="icon" type="image/png" href="/blog/img/favicon.png">
  <meta name="viewport"
        content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, shrink-to-fit=no">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  
    <meta http-equiv="Content-Security-Policy" content="upgrade-insecure-requests">
  
  <meta name="theme-color" content="#35495e">
  <meta name="description" content="小菜头的博客，主要记录学习笔记，包含：html,css,javascript,jQuery,vue等">
  <meta name="author" content="A-cai">
  <meta name="keywords" content="html,css,javascript,jQuery,vue">
  <title>Set_Map_WeakSet和WeakMap的区别 - A-cai的blog</title>

  <link  rel="stylesheet" href="https://cdn.staticfile.org/twitter-bootstrap/4.4.1/css/bootstrap.min.css" />


  <link  rel="stylesheet" href="https://cdn.staticfile.org/github-markdown-css/4.0.0/github-markdown.min.css" />
  <link  rel="stylesheet" href="/blog/lib/hint/hint.min.css" />

  
    <link  rel="stylesheet" href="https://cdn.staticfile.org/highlight.js/10.0.0/styles/atom-one-dark.min.css" />
  

  


<!-- 主题依赖的图标库，不要自行修改 -->

<link rel="stylesheet" href="//at.alicdn.com/t/font_1749284_yg9cfy8wd6.css">



<link rel="stylesheet" href="//at.alicdn.com/t/font_1736178_pjno9b9zyxs.css">


<link  rel="stylesheet" href="/blog/css/main.css" />

<!-- 自定义样式保持在最底部 -->


  <script  src="/blog/js/utils.js" ></script>
<meta name="generator" content="Hexo 4.2.0"></head>


<body>
  <header style="height: 70vh;">
    <nav id="navbar" class="navbar fixed-top  navbar-expand-lg navbar-dark scrolling-navbar">
  <div class="container">
    <a class="navbar-brand"
       href="/blog/">&nbsp;<strong>A-cai的学习笔记</strong>&nbsp;</a>

    <button id="navbar-toggler-btn" class="navbar-toggler" type="button" data-toggle="collapse"
            data-target="#navbarSupportedContent"
            aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
      <div class="animated-icon"><span></span><span></span><span></span></div>
    </button>

    <!-- Collapsible content -->
    <div class="collapse navbar-collapse" id="navbarSupportedContent">
      <ul class="navbar-nav ml-auto text-center">
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/blog/">
                <i class="iconfont icon-home-fill"></i>
                首页
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/blog/archives/">
                <i class="iconfont icon-archive-fill"></i>
                归档
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/blog/categories/">
                <i class="iconfont icon-category-fill"></i>
                分类
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/blog/tags/">
                <i class="iconfont icon-tags-fill"></i>
                标签
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/blog/about/">
                <i class="iconfont icon-user-fill"></i>
                关于
              </a>
            </li>
          
        
        
          <li class="nav-item" id="search-btn">
            <a class="nav-link" data-toggle="modal" data-target="#modalSearch">&nbsp;&nbsp;<i
                class="iconfont icon-search"></i>&nbsp;&nbsp;</a>
          </li>
        
      </ul>
    </div>
  </div>
</nav>

    <div class="banner intro-2" id="background" parallax=true
         style="background: url('/blog/img/default.png') no-repeat center center;
           background-size: cover;">
      <div class="full-bg-img">
        <div class="mask flex-center" style="background-color: rgba(0, 0, 0, 0.3)">
          <div class="container text-center white-text fade-in-up">
            <span class="h2" id="subtitle">
              
            </span>

            
              
  <div class="mt-3 post-meta">
    <i class="iconfont icon-date-fill" aria-hidden="true"></i>
    <time datetime="2020-06-26 14:05">
      2020年6月26日 下午
    </time>
  </div>


<div class="mt-1">
  
    
    <span class="post-meta mr-2">
      <i class="iconfont icon-chart"></i>
      3.1k 字
    </span>
  

  
    
    <span class="post-meta mr-2">
      <i class="iconfont icon-clock-fill"></i>
      
      
      41
       分钟
    </span>
  

  
  
    
      <!-- 不蒜子统计文章PV -->
      <span id="busuanzi_container_page_pv" style="display: none">
        <i class="iconfont icon-eye" aria-hidden="true"></i>
        <span id="busuanzi_value_page_pv"></span> 次
      </span>
    
  
</div>

            
          </div>

          
        </div>
      </div>
    </div>
  </header>

  <main>
    
      

<div class="container-fluid">
  <div class="row">
    <div class="d-none d-lg-block col-lg-2"></div>
    <div class="col-lg-8 nopadding-md">
      <div class="container nopadding-md" id="board-ctn">
        <div class="py-5" id="board">
          <div class="post-content mx-auto" id="post">
            
              <p class="note note-info">
                
                  本文最后更新于：2020年3月20日 上午
                
              </p>
            
            <article class="markdown-body">
              <p>Set 和 Map 主要的应用场景在于 <strong>数据重组</strong> 和 <strong>数据储存</strong></p>
<p>Set 是一种叫做<strong>集合</strong>的数据结构，Map 是一种叫做<strong>字典</strong>的数据结构</p>
<h3 id="1-集合（Set）"><a href="#1-集合（Set）" class="headerlink" title="1. 集合（Set）"></a>1. 集合（Set）</h3><p>ES6 新增的一种新的数据结构，类似于数组，但成员是唯一且无序的，没有重复的值。</p>
<p><strong>Set 本身是一种构造函数，用来生成 Set 数据结构。</strong></p>
<div class="hljs"><pre><code class="hljs js"><span class="hljs-keyword">new</span> <span class="hljs-built_in">Set</span>([iterable])</code></pre></div>

<p>举个例子：</p>
<div class="hljs"><pre><code class="hljs js"><span class="hljs-keyword">const</span> s = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Set</span>()
[<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">3</span>, <span class="hljs-number">2</span>, <span class="hljs-number">1</span>].forEach(<span class="hljs-function"><span class="hljs-params">x</span> =&gt;</span> s.add(x))

<span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i <span class="hljs-keyword">of</span> s) &#123;
    <span class="hljs-built_in">console</span>.log(i)	<span class="hljs-comment">// 1 2 3 4</span>
&#125;

<span class="hljs-comment">// 去重数组的重复对象</span>
<span class="hljs-keyword">let</span> arr = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">2</span>, <span class="hljs-number">1</span>, <span class="hljs-number">1</span>]
[... new <span class="hljs-built_in">Set</span>(arr)]	<span class="hljs-comment">// [1, 2, 3]</span></code></pre></div>

<p>Set 对象允许你储存任何类型的唯一值，无论是原始值或者是对象引用。</p>
<p>向 Set 加入值的时候，不会发生类型转换，所以<code>5</code>和<code>&quot;5&quot;</code>是两个不同的值。Set 内部判断两个值是否不同，使用的算法叫做“Same-value-zero equality”，它类似于<strong>精确相等</strong>运算符（<code>===</code>），主要的区别是<strong><code>NaN</code>等于自身，而精确相等运算符认为<code>NaN</code>不等于自身。</strong></p>
<div class="hljs"><pre><code class="hljs js"><span class="hljs-keyword">let</span> <span class="hljs-keyword">set</span> = new Set();
let a = NaN;
let b = NaN;
<span class="hljs-keyword">set</span>.add(a);
<span class="hljs-keyword">set</span>.add(b);
<span class="hljs-keyword">set</span> // Set &#123;<span class="hljs-literal">NaN</span>&#125;

<span class="hljs-keyword">let</span> set1 = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Set</span>()
set1.add(<span class="hljs-number">5</span>)
set1.add(<span class="hljs-string">'5'</span>)
<span class="hljs-built_in">console</span>.log([...set1])	<span class="hljs-comment">// [5, "5"]</span></code></pre></div>

<ul>
<li><p>Set 实例属性</p>
<ul>
<li><p>constructor： 构造函数</p>
</li>
<li><p>size：元素数量</p>
<div class="hljs"><pre><code class="hljs js"><span class="hljs-keyword">let</span> <span class="hljs-keyword">set</span> = new Set([1, 2, 3, 2, 1])

console.log(<span class="hljs-keyword">set</span>.length)	// undefined
console.log(<span class="hljs-keyword">set</span>.size)	// 3</code></pre></div>
</li>
</ul>
</li>
<li><p>Set 实例方法</p>
<ul>
<li><p>操作方法</p>
<ul>
<li><p>add(value)：新增，相当于 array里的push</p>
</li>
<li><p>delete(value)：存在即删除集合中value</p>
</li>
<li><p>has(value)：判断集合中是否存在 value</p>
</li>
<li><p>clear()：清空集合</p>
<hr>
<div class="hljs"><pre><code class="hljs js"><span class="hljs-keyword">let</span> <span class="hljs-keyword">set</span> = new Set()
<span class="hljs-keyword">set</span>.add(1).add(2).add(1)

<span class="hljs-keyword">set</span>.has(1)	// true
<span class="hljs-keyword">set</span>.has(3)	// false
<span class="hljs-keyword">set</span>.delete(1)	
<span class="hljs-keyword">set</span>.has(1)	// false</code></pre></div>

<p><code>Array.from</code> 方法可以将 Set 结构转为数组</p>
<div class="hljs"><pre><code class="hljs js"><span class="hljs-keyword">const</span> items = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Set</span>([<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">2</span>])
<span class="hljs-keyword">const</span> array = <span class="hljs-built_in">Array</span>.from(items)
<span class="hljs-built_in">console</span>.log(array)	<span class="hljs-comment">// [1, 2, 3]</span>
<span class="hljs-comment">// 或</span>
<span class="hljs-keyword">const</span> arr = [...items]
<span class="hljs-built_in">console</span>.log(arr)	<span class="hljs-comment">// [1, 2, 3]</span></code></pre></div>
</li>
</ul>
</li>
<li><p>遍历方法（遍历顺序为插入顺序）</p>
<ul>
<li><p>keys()：返回一个包含集合中所有键的迭代器</p>
</li>
<li><p>values()：返回一个包含集合中所有值得迭代器</p>
</li>
<li><p>entries()：返回一个包含Set对象中所有元素得键值对迭代器</p>
</li>
<li><p>forEach(callbackFn, thisArg)：用于对集合成员执行callbackFn操作，如果提供了 thisArg 参数，回调中的this会是这个参数，<strong>没有返回值</strong></p>
<div class="hljs"><pre><code class="hljs js"><span class="hljs-keyword">let</span> <span class="hljs-keyword">set</span> = new Set([1, 2, 3])
console.log(<span class="hljs-keyword">set</span>.keys())	// SetIterator &#123;<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>&#125;
<span class="hljs-built_in">console</span>.log(<span class="hljs-keyword">set</span>.values())	// SetIterator &#123;<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>&#125;
<span class="hljs-built_in">console</span>.log(<span class="hljs-keyword">set</span>.entries())	// SetIterator &#123;<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>&#125;

<span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> item <span class="hljs-keyword">of</span> <span class="hljs-keyword">set</span>.keys()) &#123;
  <span class="hljs-built_in">console</span>.log(item);
&#125;	<span class="hljs-comment">// 1	2	 3</span>
<span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> item <span class="hljs-keyword">of</span> <span class="hljs-keyword">set</span>.entries()) &#123;
  <span class="hljs-built_in">console</span>.log(item);
&#125;	<span class="hljs-comment">// [1, 1]	[2, 2]	[3, 3]</span>

<span class="hljs-keyword">set</span>.forEach((value, key) =&gt; &#123;
    <span class="hljs-built_in">console</span>.log(key + <span class="hljs-string">' : '</span> + value)
&#125;)	<span class="hljs-comment">// 1 : 1	2 : 2	3 : 3</span>
<span class="hljs-built_in">console</span>.log([...set])	<span class="hljs-comment">// [1, 2, 3]</span></code></pre></div>

<p>Set 可默认遍历，默认迭代器生成函数是 values() 方法</p>
<div class="hljs"><pre><code class="hljs js"><span class="hljs-built_in">Set</span>.prototype[<span class="hljs-built_in">Symbol</span>.iterator] === <span class="hljs-built_in">Set</span>.prototype.values	<span class="hljs-comment">// true</span></code></pre></div>

<p>所以， Set可以使用 map、filter 方法</p>
<div class="hljs"><pre><code class="hljs js"><span class="hljs-keyword">let</span> <span class="hljs-keyword">set</span> = new Set([1, 2, 3])
<span class="hljs-keyword">set</span> = new Set([...<span class="hljs-keyword">set</span>].map(item =&gt; item * 2))
console.log([...<span class="hljs-keyword">set</span>])	// [2, 4, 6]

<span class="hljs-keyword">set</span> = new Set([...<span class="hljs-keyword">set</span>].filter(item =&gt; (item &gt;= 4)))
console.log([...<span class="hljs-keyword">set</span>])	//[4, 6]</code></pre></div>

<p>因此，Set 很容易实现交集（Intersect）、并集（Union）、差集（Difference）</p>
<div class="hljs"><pre><code class="hljs js"><span class="hljs-keyword">let</span> set1 = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Set</span>([<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>])
<span class="hljs-keyword">let</span> set2 = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Set</span>([<span class="hljs-number">4</span>, <span class="hljs-number">3</span>, <span class="hljs-number">2</span>])

<span class="hljs-keyword">let</span> intersect = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Set</span>([...set1].filter(<span class="hljs-function"><span class="hljs-params">value</span> =&gt;</span> set2.has(value)))
<span class="hljs-keyword">let</span> union = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Set</span>([...set1, ...set2])
<span class="hljs-keyword">let</span> difference = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Set</span>([...set1].filter(<span class="hljs-function"><span class="hljs-params">value</span> =&gt;</span> !set2.has(value)))

<span class="hljs-built_in">console</span>.log(intersect)	<span class="hljs-comment">// Set &#123;2, 3&#125;</span>
<span class="hljs-built_in">console</span>.log(union)		<span class="hljs-comment">// Set &#123;1, 2, 3, 4&#125;</span>
<span class="hljs-built_in">console</span>.log(difference)	<span class="hljs-comment">// Set &#123;1&#125;</span></code></pre></div>

</li>
</ul>
</li>
</ul>
</li>
</ul>
<h3 id="2-WeakSet"><a href="#2-WeakSet" class="headerlink" title="2. WeakSet"></a>2. WeakSet</h3><p>WeakSet 对象允许你将<strong>弱引用对象</strong>储存在一个集合中</p>
<p>WeakSet 与 Set 的区别：</p>
<ul>
<li>WeakSet 只能储存对象引用，不能存放值，而 Set 对象都可以</li>
<li>WeakSet 对象中储存的对象值都是被弱引用的，即垃圾回收机制不考虑 WeakSet 对该对象的应用，如果没有其他的变量或属性引用这个对象值，则这个对象将会被垃圾回收掉（不考虑该对象还存在于 WeakSet 中），所以，WeakSet 对象里有多少个成员元素，取决于垃圾回收机制有没有运行，运行前后成员个数可能不一致，遍历结束之后，有的成员可能取不到了（被垃圾回收了），WeakSet 对象是无法被遍历的（ES6 规定 WeakSet 不可遍历），也没有办法拿到它包含的所有元素</li>
</ul>
<p>属性：</p>
<ul>
<li><p>constructor：构造函数，任何一个具有 Iterable 接口的对象，都可以作参数</p>
<div class="hljs"><pre><code class="hljs js"><span class="hljs-keyword">const</span> arr = [[<span class="hljs-number">1</span>, <span class="hljs-number">2</span>], [<span class="hljs-number">3</span>, <span class="hljs-number">4</span>]]
<span class="hljs-keyword">const</span> weakset = <span class="hljs-keyword">new</span> <span class="hljs-built_in">WeakSet</span>(arr)
<span class="hljs-built_in">console</span>.log(weakset)</code></pre></div>

</li>
</ul>
<p><img src="https://user-images.githubusercontent.com/19721451/54000884-27290900-4184-11e9-92f0-4d19ac6d080b.png" srcset="/blog/img/loading.gif" alt="img"></p>
<p>方法：</p>
<ul>
<li>add(value)：在WeakSet 对象中添加一个元素value</li>
<li>has(value)：判断 WeakSet 对象中是否包含value</li>
<li>delete(value)：删除元素 value</li>
<li>clear()：清空所有元素，<strong>注意该方法已废弃</strong></li>
</ul>
<div class="hljs"><pre><code class="hljs js"><span class="hljs-keyword">var</span> ws = <span class="hljs-keyword">new</span> <span class="hljs-built_in">WeakSet</span>()
<span class="hljs-keyword">var</span> obj = &#123;&#125;
<span class="hljs-keyword">var</span> foo = &#123;&#125;

ws.add(<span class="hljs-built_in">window</span>)
ws.add(obj)

ws.has(<span class="hljs-built_in">window</span>)	<span class="hljs-comment">// true</span>
ws.has(foo)	<span class="hljs-comment">// false</span>

ws.delete(<span class="hljs-built_in">window</span>)	<span class="hljs-comment">// true</span>
ws.has(<span class="hljs-built_in">window</span>)	<span class="hljs-comment">// false</span></code></pre></div>

<h3 id="3-字典（Map）"><a href="#3-字典（Map）" class="headerlink" title="3. 字典（Map）"></a>3. 字典（Map）</h3><p>集合 与 字典 的区别：</p>
<ul>
<li>共同点：集合、字典 可以储存不重复的值</li>
<li>不同点：集合 是以 [value, value]的形式储存元素，字典 是以 [key, value] 的形式储存</li>
</ul>
<div class="hljs"><pre><code class="hljs js"><span class="hljs-keyword">const</span> m = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Map</span>()
<span class="hljs-keyword">const</span> o = &#123;<span class="hljs-attr">p</span>: <span class="hljs-string">'haha'</span>&#125;
m.set(o, <span class="hljs-string">'content'</span>)
m.get(o)	<span class="hljs-comment">// content</span>

m.has(o)	<span class="hljs-comment">// true</span>
m.delete(o)	<span class="hljs-comment">// true</span>
m.has(o)	<span class="hljs-comment">// false</span></code></pre></div>

<p><strong>任何具有 Iterator 接口、且每个成员都是一个双元素的数组的数据结构</strong>都可以当作<code>Map</code>构造函数的参数，例如：</p>
<div class="hljs"><pre><code class="hljs js"><span class="hljs-keyword">const</span> <span class="hljs-keyword">set</span> = new Set([
  ['foo', 1],
  ['bar', 2]
]);
const m1 = new Map(<span class="hljs-keyword">set</span>);
m1.<span class="hljs-keyword">get</span>('foo') // 1

const m2 = new Map([['baz', 3]]);
const m3 = new Map(m2);
m3.<span class="hljs-keyword">get</span>('baz') // 3</code></pre></div>

<p>如果读取一个未知的键，则返回<code>undefined</code>。</p>
<div class="hljs"><pre><code class="hljs js"><span class="hljs-keyword">new</span> <span class="hljs-built_in">Map</span>().get(<span class="hljs-string">'asfddfsasadf'</span>)
<span class="hljs-comment">// undefined</span></code></pre></div>

<p>注意，只有对同一个对象的引用，Map 结构才将其视为同一个键。这一点要非常小心。</p>
<div class="hljs"><pre><code class="hljs js"><span class="hljs-keyword">const</span> map = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Map</span>();

map.set([<span class="hljs-string">'a'</span>], <span class="hljs-number">555</span>);
map.get([<span class="hljs-string">'a'</span>]) <span class="hljs-comment">// undefined</span></code></pre></div>

<p>上面代码的<code>set</code>和<code>get</code>方法，表面是针对同一个键，但实际上这是两个值，内存地址是不一样的，因此<code>get</code>方法无法读取该键，返回<code>undefined</code>。</p>
<p>由上可知，Map 的键实际上是跟内存地址绑定的，只要内存地址不一样，就视为两个键。这就解决了同名属性碰撞（clash）的问题，我们扩展别人的库的时候，如果使用对象作为键名，就不用担心自己的属性与原作者的属性同名。</p>
<p>如果 Map 的键是一个简单类型的值（数字、字符串、布尔值），则只要两个值严格相等，Map 将其视为一个键，比如<code>0</code>和<code>-0</code>就是一个键，布尔值<code>true</code>和字符串<code>true</code>则是两个不同的键。另外，<code>undefined</code>和<code>null</code>也是两个不同的键。虽然<code>NaN</code>不严格相等于自身，但 Map 将其视为同一个键。</p>
<div class="hljs"><pre><code class="hljs js"><span class="hljs-keyword">let</span> map = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Map</span>();

map.set(<span class="hljs-number">-0</span>, <span class="hljs-number">123</span>);
map.get(+<span class="hljs-number">0</span>) <span class="hljs-comment">// 123</span>

map.set(<span class="hljs-literal">true</span>, <span class="hljs-number">1</span>);
map.set(<span class="hljs-string">'true'</span>, <span class="hljs-number">2</span>);
map.get(<span class="hljs-literal">true</span>) <span class="hljs-comment">// 1</span>

map.set(<span class="hljs-literal">undefined</span>, <span class="hljs-number">3</span>);
map.set(<span class="hljs-literal">null</span>, <span class="hljs-number">4</span>);
map.get(<span class="hljs-literal">undefined</span>) <span class="hljs-comment">// 3</span>

map.set(<span class="hljs-literal">NaN</span>, <span class="hljs-number">123</span>);
map.get(<span class="hljs-literal">NaN</span>) <span class="hljs-comment">// 123</span></code></pre></div>

<p>Map 的属性及方法</p>
<p>属性：</p>
<ul>
<li><p>constructor：构造函数</p>
</li>
<li><p>size：返回字典中所包含的元素个数</p>
<div class="hljs"><pre><code class="hljs js"><span class="hljs-keyword">const</span> map = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Map</span>([
  [<span class="hljs-string">'name'</span>, <span class="hljs-string">'An'</span>],
  [<span class="hljs-string">'des'</span>, <span class="hljs-string">'JS'</span>]
]);

map.size <span class="hljs-comment">// 2</span></code></pre></div>

</li>
</ul>
<p>操作方法：</p>
<ul>
<li>set(key, value)：向字典中添加新元素</li>
<li>get(key)：通过键查找特定的数值并返回</li>
<li>has(key)：判断字典中是否存在键key</li>
<li>delete(key)：通过键 key 从字典中移除对应的数据</li>
<li>clear()：将这个字典中的所有元素删除</li>
</ul>
<p>遍历方法</p>
<ul>
<li>Keys()：将字典中包含的所有键名以迭代器形式返回</li>
<li>values()：将字典中包含的所有数值以迭代器形式返回</li>
<li>entries()：返回所有成员的迭代器</li>
<li>forEach()：遍历字典的所有成员</li>
</ul>
<div class="hljs"><pre><code class="hljs js"><span class="hljs-keyword">const</span> map = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Map</span>([
            [<span class="hljs-string">'name'</span>, <span class="hljs-string">'An'</span>],
            [<span class="hljs-string">'des'</span>, <span class="hljs-string">'JS'</span>]
        ]);
<span class="hljs-built_in">console</span>.log(map.entries())	<span class="hljs-comment">// MapIterator &#123;"name" =&gt; "An", "des" =&gt; "JS"&#125;</span>
<span class="hljs-built_in">console</span>.log(map.keys()) <span class="hljs-comment">// MapIterator &#123;"name", "des"&#125;</span></code></pre></div>

<p>Map 结构的默认遍历器接口（<code>Symbol.iterator</code>属性），就是<code>entries</code>方法。</p>
<div class="hljs"><pre><code class="hljs js">map[<span class="hljs-built_in">Symbol</span>.iterator] === map.entries
<span class="hljs-comment">// true</span></code></pre></div>

<p>Map 结构转为数组结构，比较快速的方法是使用扩展运算符（<code>...</code>）。</p>
<p>对于 forEach ，看一个例子</p>
<div class="hljs"><pre><code class="hljs js"><span class="hljs-keyword">const</span> reporter = &#123;
  report: <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">key, value</span>) </span>&#123;
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Key: %s, Value: %s"</span>, key, value);
  &#125;
&#125;;

<span class="hljs-keyword">let</span> map = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Map</span>([
    [<span class="hljs-string">'name'</span>, <span class="hljs-string">'An'</span>],
    [<span class="hljs-string">'des'</span>, <span class="hljs-string">'JS'</span>]
])
map.forEach(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">value, key, map</span>) </span>&#123;
  <span class="hljs-keyword">this</span>.report(key, value);
&#125;, reporter);
<span class="hljs-comment">// Key: name, Value: An</span>
<span class="hljs-comment">// Key: des, Value: JS</span></code></pre></div>

<p>在这个例子中， forEach 方法的回调函数的 this，就指向 reporter</p>
<p><strong>与其他数据结构的相互转换</strong></p>
<ol>
<li><p>Map 转 Array</p>
<div class="hljs"><pre><code class="hljs js"><span class="hljs-keyword">const</span> map = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Map</span>([[<span class="hljs-number">1</span>, <span class="hljs-number">1</span>], [<span class="hljs-number">2</span>, <span class="hljs-number">2</span>], [<span class="hljs-number">3</span>, <span class="hljs-number">3</span>]])
<span class="hljs-built_in">console</span>.log([...map])	<span class="hljs-comment">// [[1, 1], [2, 2], [3, 3]]</span></code></pre></div>
</li>
<li><p>Array 转 Map</p>
<div class="hljs"><pre><code class="hljs js"><span class="hljs-keyword">const</span> map = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Map</span>([[<span class="hljs-number">1</span>, <span class="hljs-number">1</span>], [<span class="hljs-number">2</span>, <span class="hljs-number">2</span>], [<span class="hljs-number">3</span>, <span class="hljs-number">3</span>]])
<span class="hljs-built_in">console</span>.log(map)	<span class="hljs-comment">// Map &#123;1 =&gt; 1, 2 =&gt; 2, 3 =&gt; 3&#125;</span></code></pre></div>
</li>
<li><p>Map 转 Object</p>
<p>因为 Object 的键名都为字符串，而Map 的键名为对象，所以转换的时候会把非字符串键名转换为字符串键名。</p>
<div class="hljs"><pre><code class="hljs js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">mapToObj</span>(<span class="hljs-params">map</span>) </span>&#123;
    <span class="hljs-keyword">let</span> obj = <span class="hljs-built_in">Object</span>.create(<span class="hljs-literal">null</span>)
    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> [key, value] <span class="hljs-keyword">of</span> map) &#123;
        obj[key] = value
    &#125;
    <span class="hljs-keyword">return</span> obj
&#125;
<span class="hljs-keyword">const</span> map = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Map</span>().set(<span class="hljs-string">'name'</span>, <span class="hljs-string">'An'</span>).set(<span class="hljs-string">'des'</span>, <span class="hljs-string">'JS'</span>)
mapToObj(map)  <span class="hljs-comment">// &#123;name: "An", des: "JS"&#125;</span></code></pre></div>
</li>
<li><p>Object 转 Map</p>
<div class="hljs"><pre><code class="hljs js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">objToMap</span>(<span class="hljs-params">obj</span>) </span>&#123;
    <span class="hljs-keyword">let</span> map = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Map</span>()
    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> key <span class="hljs-keyword">of</span> <span class="hljs-built_in">Object</span>.keys(obj)) &#123;
        map.set(key, obj[key])
    &#125;
    <span class="hljs-keyword">return</span> map
&#125;

objToMap(&#123;<span class="hljs-string">'name'</span>: <span class="hljs-string">'An'</span>, <span class="hljs-string">'des'</span>: <span class="hljs-string">'JS'</span>&#125;) <span class="hljs-comment">// Map &#123;"name" =&gt; "An", "des" =&gt; "JS"&#125;</span></code></pre></div>
</li>
<li><p>Map 转 JSON</p>
<div class="hljs"><pre><code class="hljs js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">mapToJson</span>(<span class="hljs-params">map</span>) </span>&#123;
    <span class="hljs-keyword">return</span> <span class="hljs-built_in">JSON</span>.stringify([...map])
&#125;

<span class="hljs-keyword">let</span> map = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Map</span>().set(<span class="hljs-string">'name'</span>, <span class="hljs-string">'An'</span>).set(<span class="hljs-string">'des'</span>, <span class="hljs-string">'JS'</span>)
mapToJson(map)	<span class="hljs-comment">// [["name","An"],["des","JS"]]</span></code></pre></div>
</li>
<li><p>JSON 转 Map</p>
<div class="hljs"><pre><code class="hljs js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">jsonToStrMap</span>(<span class="hljs-params">jsonStr</span>) </span>&#123;
  <span class="hljs-keyword">return</span> objToMap(<span class="hljs-built_in">JSON</span>.parse(jsonStr));
&#125;

jsonToStrMap(<span class="hljs-string">'&#123;"name": "An", "des": "JS"&#125;'</span>) <span class="hljs-comment">// Map &#123;"name" =&gt; "An", "des" =&gt; "JS"&#125;</span></code></pre></div>

</li>
</ol>
<h3 id="4-WeakMap"><a href="#4-WeakMap" class="headerlink" title="4. WeakMap"></a>4. WeakMap</h3><p>WeakMap 对象是一组键值对的集合，其中的<strong>键是弱引用对象，而值可以是任意</strong>。</p>
<p><strong>注意，WeakMap 弱引用的只是键名，而不是键值。键值依然是正常引用。</strong></p>
<p>WeakMap 中，每个键对自己所引用对象的引用都是弱引用，在没有其他引用和该键引用同一对象，这个对象将会被垃圾回收（相应的key则变成无效的），所以，WeakMap 的 key 是不可枚举的。</p>
<p>属性：</p>
<ul>
<li>constructor：构造函数</li>
</ul>
<p>方法：</p>
<ul>
<li>has(key)：判断是否有 key 关联对象</li>
<li>get(key)：返回key关联对象（没有则则返回 undefined）</li>
<li>set(key)：设置一组key关联对象</li>
<li>delete(key)：移除 key 的关联对象</li>
</ul>
<div class="hljs"><pre><code class="hljs js"><span class="hljs-keyword">let</span> myElement = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'logo'</span>);
<span class="hljs-keyword">let</span> myWeakmap = <span class="hljs-keyword">new</span> <span class="hljs-built_in">WeakMap</span>();

myWeakmap.set(myElement, &#123;<span class="hljs-attr">timesClicked</span>: <span class="hljs-number">0</span>&#125;);

myElement.addEventListener(<span class="hljs-string">'click'</span>, <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>&#123;
  <span class="hljs-keyword">let</span> logoData = myWeakmap.get(myElement);
  logoData.timesClicked++;
&#125;, <span class="hljs-literal">false</span>);</code></pre></div>

<h1 id="介绍下Set-Map-WeakSet和WeakMap的区别"><a href="#介绍下Set-Map-WeakSet和WeakMap的区别" class="headerlink" title="介绍下Set_Map_WeakSet和WeakMap的区别"></a>介绍下Set_Map_WeakSet和WeakMap的区别</h1><h3 id="5-总结"><a href="#5-总结" class="headerlink" title="5. 总结"></a>5. 总结</h3><ul>
<li>Set<ul>
<li>成员唯一、无序且不重复</li>
<li>[value, value]，键值与键名是一致的（或者说只有键值，没有键名）</li>
<li>可以遍历，方法有：add、delete、has</li>
</ul>
</li>
<li>WeakSet<ul>
<li>成员都是对象</li>
<li>成员都是弱引用，可以被垃圾回收机制回收，可以用来保存DOM节点，不容易造成内存泄漏</li>
<li>不能遍历，方法有add、delete、has</li>
</ul>
</li>
<li>Map<ul>
<li>本质上是键值对的集合，类似集合</li>
<li>可以遍历，方法很多可以跟各种数据格式转换</li>
</ul>
</li>
<li>WeakMap<ul>
<li>只接受对象作为键名（null除外），不接受其他类型的值作为键名</li>
<li>键名是弱引用，键值可以是任意的，键名所指向的对象可以被垃圾回收，此时键名是无效的</li>
<li>不能遍历，方法有get、set、has、delete</li>
</ul>
</li>
</ul>
<h3 id="6-扩展：Object与Set、Map"><a href="#6-扩展：Object与Set、Map" class="headerlink" title="6. 扩展：Object与Set、Map"></a>6. 扩展：Object与Set、Map</h3><ol>
<li><p>Object 与 Set</p>
<div class="hljs"><pre><code class="hljs js"><span class="hljs-comment">// Object</span>
<span class="hljs-keyword">const</span> properties1 = &#123;
    <span class="hljs-string">'width'</span>: <span class="hljs-number">1</span>,
    <span class="hljs-string">'height'</span>: <span class="hljs-number">1</span>
&#125;
<span class="hljs-built_in">console</span>.log(properties1[<span class="hljs-string">'width'</span>]? <span class="hljs-literal">true</span>: <span class="hljs-literal">false</span>) <span class="hljs-comment">// true</span>

<span class="hljs-comment">// Set</span>
<span class="hljs-keyword">const</span> properties2 = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Set</span>()
properties2.add(<span class="hljs-string">'width'</span>)
properties2.add(<span class="hljs-string">'height'</span>)
<span class="hljs-built_in">console</span>.log(properties2.has(<span class="hljs-string">'width'</span>)) <span class="hljs-comment">// true</span></code></pre></div>
</li>
<li><p>Object 与 Map</p>
</li>
</ol>
<h1 id="ES6-WeakMap和WeakSet的使用场景"><a href="#ES6-WeakMap和WeakSet的使用场景" class="headerlink" title="ES6 WeakMap和WeakSet的使用场景"></a>ES6 WeakMap和WeakSet的使用场景</h1><p>JS 中的对象（Object），本质上是键值对的集合（hash 结构）</p>
<div class="hljs"><pre><code class="hljs js"><span class="hljs-keyword">const</span> data = &#123;&#125;;
<span class="hljs-keyword">const</span> element = <span class="hljs-built_in">document</span>.getElementsByClassName(<span class="hljs-string">'App'</span>);

data[element] = <span class="hljs-string">'metadata'</span>;
<span class="hljs-built_in">console</span>.log(data[<span class="hljs-string">'[object HTMLCollection]'</span>]) <span class="hljs-comment">// "metadata"</span></code></pre></div>

<p>但当以一个DOM节点作为对象 data 的键，对象会被自动转化为字符串[Object HTMLCollection]，所以说，Object 结构提供了 <strong>字符串-值</strong> 对应，Map则提供了 <strong>值-值</strong> 的对应</p>
<p>本</p>
<p>JavaScript垃圾回收是一种内存管理技术。在这种技术中，不再被引用的对象会被自动删除，而与其相关的资源也会被一同回收。</p>
<p>Map和Set中对象的引用都是强类型化的，并不会允许垃圾回收。这样一来，如果Map和Set中引用了不再需要的大型对象，如已经从DOM树中删除的DOM元素，那么其回收代价是昂贵的。</p>
<p>为了解决这个问题，ES6还引入了另外两种新的数据结构，即称为WeakMap和WeakSet的弱集合。这些集合之所以是“<strong>弱的</strong>”，是因为它们允许从内存中清除不再需要的被这些集合所引用的对象。</p>
<p>使用场景：<strong>储存 DOM 节点，而不用担心这些节点从文档移除时，会引发内存泄漏</strong>。</p>

            </article>
            <hr>
            <div>
              <div class="post-metas mb-3">
                
                
              </div>
              
                <p class="note note-warning">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-sa/4.0/deed.zh" target="_blank" rel="nofollow noopener noopener">CC BY-SA 4.0 协议</a> ，转载请注明出处！</p>
              
              
                <div class="post-prevnext row">
                  <div class="post-prev col-6">
                    
                    
                      <a href="/blog/2020/06/26/ES5%E4%B8%8EES6%E7%BB%A7%E6%89%BF%E7%9A%84%E5%8C%BA%E5%88%AB/">
                        <i class="iconfont icon-arrowleft"></i>
                        <span class="hidden-mobile">ES5与ES6继承的区别</span>
                        <span class="visible-mobile">上一篇</span>
                      </a>
                    
                  </div>
                  <div class="post-next col-6">
                    
                    
                      <a href="/blog/2020/06/26/%E5%87%BD%E6%95%B0%E9%98%B2%E6%8A%96%E4%B8%8E%E8%8A%82%E6%B5%81/">
                        <span class="hidden-mobile">函数防抖与节流</span>
                        <span class="visible-mobile">下一篇</span>
                        <i class="iconfont icon-arrowright"></i>
                      </a>
                    
                  </div>
                </div>
              
            </div>

            
              <!-- Comments -->
              <div class="comments" id="comments">
                
                

              </div>
            
          </div>
        </div>
      </div>
    </div>
    
      <div class="d-none d-lg-block col-lg-2 toc-container" id="toc-ctn">
        <div id="toc">
  <p class="toc-header"><i class="iconfont icon-list"></i>&nbsp;目录</p>
  <div id="tocbot"></div>
</div>

      </div>
    
  </div>
</div>

<!-- Custom -->


    
  </main>

  
    <a id="scroll-top-button" href="#" role="button">
      <i class="iconfont icon-arrowup" aria-hidden="true"></i>
    </a>
  

  
    <div class="modal fade" id="modalSearch" tabindex="-1" role="dialog" aria-labelledby="ModalLabel"
     aria-hidden="true">
  <div class="modal-dialog modal-dialog-scrollable modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header text-center">
        <h4 class="modal-title w-100 font-weight-bold">搜索</h4>
        <button type="button" id="local-search-close" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body mx-3">
        <div class="md-form mb-5">
          <input type="text" id="local-search-input" class="form-control validate">
          <label data-error="x" data-success="v"
                 for="local-search-input">关键词</label>
        </div>
        <div class="list-group" id="local-search-result"></div>
      </div>
    </div>
  </div>
</div>
  

  

  

  <footer class="mt-5">
  <div class="text-center py-3">
    <div>
      <a href="https://hexo.io" target="_blank" rel="nofollow noopener"><span>Hexo</span></a>
      <i class="iconfont icon-love"></i>
      <a href="https://github.com/fluid-dev/hexo-theme-fluid" target="_blank" rel="nofollow noopener">
        <span>Fluid</span></a>
    </div>
    

    

    
  </div>
</footer>

<!-- SCRIPTS -->
<script  src="https://cdn.staticfile.org/jquery/3.4.1/jquery.min.js" ></script>
<script  src="https://cdn.staticfile.org/twitter-bootstrap/4.4.1/js/bootstrap.min.js" ></script>
<script  src="/blog/js/debouncer.js" ></script>
<script  src="/blog/js/main.js" ></script>

<!-- Plugins -->


  
    <script  src="/blog/js/lazyload.js" ></script>
  



  <script defer src="https://cdn.staticfile.org/clipboard.js/2.0.6/clipboard.min.js" ></script>
  <script  src="/blog/js/clipboard-use.js" ></script>



  <script defer src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js" ></script>





  <script  src="https://cdn.staticfile.org/tocbot/4.11.1/tocbot.min.js" ></script>
  <script>
    $(document).ready(function () {
      var boardCtn = $('#board-ctn');
      var boardTop = boardCtn.offset().top;

      tocbot.init({
        tocSelector: '#tocbot',
        contentSelector: 'article.markdown-body',
        headingSelector: 'h1,h2,h3,h4,h5,h6',
        linkClass: 'tocbot-link',
        activeLinkClass: 'tocbot-active-link',
        listClass: 'tocbot-list',
        isCollapsedClass: 'tocbot-is-collapsed',
        collapsibleClass: 'tocbot-is-collapsible',
        collapseDepth: 0,
        scrollSmooth: true,
        headingsOffset: -boardTop
      });
      if ($('.toc-list-item').length > 0) {
        $('#toc').css('visibility', 'visible');
      }
    });
  </script>



  <script  src="https://cdn.staticfile.org/typed.js/2.0.11/typed.min.js" ></script>
  <script>
    var typed = new Typed('#subtitle', {
      strings: [
        '  ',
        "Set_Map_WeakSet和WeakMap的区别&nbsp;",
      ],
      cursorChar: "|",
      typeSpeed: 70,
      loop: true,
    });
    typed.stop();
    $(document).ready(function () {
      $(".typed-cursor").addClass("h2");
      typed.start();
    });
  </script>



  <script  src="https://cdn.staticfile.org/anchor-js/4.2.2/anchor.min.js" ></script>
  <script>
    anchors.options = {
      placement: "right",
      visible: "hover",
      
    };
    var el = "h1,h2,h3,h4,h5,h6".split(",");
    var res = [];
    for (item of el) {
      res.push(".markdown-body > " + item)
    }
    anchors.add(res.join(", "))
  </script>



  <script  src="/blog/js/local-search.js" ></script>
  <script>
    var path = "/blog/local-search.xml";
    var inputArea = document.querySelector("#local-search-input");
    inputArea.onclick = function () {
      searchFunc(path, 'local-search-input', 'local-search-result');
      this.onclick = null
    }
  </script>



  <script  src="https://cdn.staticfile.org/fancybox/3.5.7/jquery.fancybox.min.js" ></script>
  <link  rel="stylesheet" href="https://cdn.staticfile.org/fancybox/3.5.7/jquery.fancybox.min.css" />

  <script>
    $('#post img:not(.no-zoom img, img[no-zoom]), img[zoom]').each(
      function () {
        var element = document.createElement('a');
        $(element).attr('data-fancybox', 'images');
        $(element).attr('href', $(this).attr('src'));
        $(this).wrap(element);
      }
    );
  </script>







  
  
    <script>
      !function (e, t, a) {
        function r() {
          for (var e = 0; e < s.length; e++) s[e].alpha <= 0 ? (t.body.removeChild(s[e].el), s.splice(e, 1)) : (s[e].y--, s[e].scale += .004, s[e].alpha -= .013, s[e].el.style.cssText = "left:" + s[e].x + "px;top:" + s[e].y + "px;opacity:" + s[e].alpha + ";transform:scale(" + s[e].scale + "," + s[e].scale + ") rotate(45deg);background:" + s[e].color + ";z-index:99999");
          requestAnimationFrame(r)
        }

        function n() {
          var t = "function" == typeof e.onclick && e.onclick;
          e.onclick = function (e) {
            t && t(), o(e)
          }
        }

        function o(e) {
          var a = t.createElement("div");
          a.className = "heart", s.push({
            el: a,
            x: e.clientX - 5,
            y: e.clientY - 5,
            scale: 1,
            alpha: 1,
            color: c()
          }), t.body.appendChild(a)
        }

        function i(e) {
          var a = t.createElement("style");
          a.type = "text/css";
          try {
            a.appendChild(t.createTextNode(e))
          } catch (t) {
            a.styleSheet.cssText = e
          }
          t.getElementsByTagName("head")[0].appendChild(a)
        }

        function c() {
          return "rgb(" + ~~(255 * Math.random()) + "," + ~~(255 * Math.random()) + "," + ~~(255 * Math.random()) + ")"
        }

        var s = [];
        e.requestAnimationFrame = e.requestAnimationFrame || e.webkitRequestAnimationFrame || e.mozRequestAnimationFrame || e.oRequestAnimationFrame || e.msRequestAnimationFrame || function (e) {
          setTimeout(e, 1e3 / 60)
        }, i(".heart{width: 10px;height: 10px;position: fixed;background: #f00;transform: rotate(45deg);-webkit-transform: rotate(45deg);-moz-transform: rotate(45deg);}.heart:after,.heart:before{content: '';width: inherit;height: inherit;background: inherit;border-radius: 50%;-webkit-border-radius: 50%;-moz-border-radius: 50%;position: fixed;}.heart:after{top: -5px;}.heart:before{left: -5px;}"), n(), r()
      }(window, document);
    </script>
  













</body>
</html>
